# vim: ai ts=2 sts=2 et sw=2

import logging

import pygame
from pygame.locals import *

import utils

import widget
import container

class ConsoleHandler(logging.Handler):
  def __init__(self, console):
    logging.Handler.__init__(self)
    self.console = console

  def emit(self, record):
    self.console.appendLine(self.format(record))

class ConsoleWindow(container.Container):
  def __init__(self, left, top, width, height, font):
    container.Container.__init__(self, left, top, width, height)

    self.console = Console(0, 10, width, height - 10, font)
    self.dragger = container.Dragger(0, 0, width, 10)

    self.add(self.console)
    self.add(self.dragger)

class Console(widget.Widget):
  def __init__(self, left, top, width, height, font):
    widget.Widget.__init__(self, left, top, width, height)

    self.font = font

    self.backgroundLayer = pygame.Surface((self.rect.width, self.rect.height))
    self.backgroundLayer.set_alpha(128)
    self.textLayer = pygame.Surface((self.rect.width, self.rect.height))
    self.textLayer.set_colorkey((0, 0, 0))

    self.lines = []

  def onMouseButtonUp(self, event):
    return True
  
  def onMouseButtonDown(self, event):
    return True

  def update(self):
    pygame.draw.rect(self.backgroundLayer, (0, 0, 0), (0, 0, self.rect.width, self.rect.height))

    self.textLayer.fill((0, 0, 0))
    top = 0
    for line in self.lines:
      lineSurface = self.font.render(line, 1, (255, 255, 255))
      self.textLayer.blit(lineSurface, (0, top))
      top += lineSurface.get_height()

  def onDraw(self, surface):
    surface.blit(self.backgroundLayer, self.screenRect)
    surface.blit(self.textLayer, self.screenRect)

  def appendLine(self, line):
    self.lines.append(line)
    self.update()

